using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using SqlSugar;
using xjjxmm.infrastructure.Common;
using xjjxmm.infrastructure.webs.filter;
using XjjXmm.Infrastructure.Common;
using XjjXmm.Infrastructure.Configuration;
using XjjXmm.Infrastructure.ToolKit;
using XjjXmm.Infrastructure.Webs.Route;

namespace xjjxmm.infrastructure.SetUp;

public static class ControllerSetUp
{
	public static WebApplicationBuilder RegistController(this WebApplicationBuilder builder)
	{
		var frameConfig = ConfigHelper.GetSection<FrameworkConfig>("xjjxmm.framework");
		//用newtionsoftjson 代替默认方案， 
		builder.Services.AddControllers(opt =>
			{            // 路由参数在此处仍然是有效的，比如添加一个版本号
				if (!frameConfig?.Prefix?.IsNullOrEmpty()??false)
				{
					opt.UseCentralRoutePrefix(new RouteAttribute(frameConfig!.Prefix));
				}
			})
			.AddMvcOptions(t =>
			{
				
				if (frameConfig?.UsePrettyResult == "1")
				{
					t.Filters.Add<MvcResultFilter>();
				}
				
				t.Filters.Add<MvcExceptionFilter>();

				
				//t.Filters.Add(new AuthorizeFilter());
			}).AddNewtonsoftJson(option =>
			{
				option.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
				option.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
				option.SerializerSettings.Converters.Add(new LongJsonConverter());
				//option.ContractResolver = new CamelCasePropertyNamesContractResolver();


            }).AddControllersAsServices();

		return builder;
	}

	
}